package com.jungle.common.config;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;

import java.sql.*;

public class GeometryTypeHandler1 implements TypeHandler<Geometry> {

    @Override
    public void setParameter(PreparedStatement ps, int i, Geometry parameter, JdbcType jdbcType) throws SQLException {
        if (parameter != null) {
            ps.setString(i, parameter.toText());
        } else {
            ps.setNull(i, Types.VARCHAR);
        }
    }

    @Override
    public Geometry getResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        if (value != null) {
            return wktToGeometry(value);
        }
        return null;
    }

    @Override
    public Geometry getResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        if (value != null) {
            return wktToGeometry(value);
        }
        return null;
    }

    @Override
    public Geometry getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        if (value != null) {
            return wktToGeometry(value);
        }
        return null;
    }

    private Geometry wktToGeometry(String value) {
        // 根据具体的Geometry库来实现将字符串转换为Geometry对象的逻辑
        // 这里以JTS库为例
        WKTReader reader = new WKTReader();
        try {
            return reader.read(value);
        } catch (ParseException e) {
            throw new RuntimeException("Failed to parse WKT", e);
        }
    }

}